package cn.tedu.logistics.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.tedu.logistics.bean.Depository;
import cn.tedu.logistics.dao.DepositoryDao;

@Service
public class DepositoryServiceImpl implements DepositoryService {
	@Autowired
	private DepositoryDao depoDao;
	
	//根据自身id查询商品信息
	@Override
	public Depository selectById(Long depositoryInfoId) {
		Depository depo = depoDao.selectById(depositoryInfoId);
		if(depo!=null) {
			return depo;
		}else {
			return null;
		}
	}
	
	//根据商店ID查询库存信息
	@Override
	public List<Depository> selectDepoByShopId(String shopId) {
		QueryWrapper<Depository> qw = new QueryWrapper();
		qw.eq("shop_id",shopId);
		List<Depository> lists = depoDao.selectList(qw);
		//检查商品的数量，若数量为0，在显示之前自动删除
		if(lists!=null&&lists.size()!=0) {
			for(Depository depo:lists) {
				if(depo.getGoodsInventory()==0) {
					depoDao.deleteById(depo.getDepositoryInfoId());
				}
			}
		}
		if(lists!=null&&lists.size()!=0) {
			return lists;
		}
		else {
			return null;
		}
	}
	@Override
	public void updDepository(Depository depo) {
		depo.setUpdateTime(new Date());
		depoDao.updateById(depo);
	}
	//新增进货单同时更新仓储
	@Override
	public void depositoryAdd(String shopId,String goodsName,Integer num) {
		QueryWrapper<Depository> queryWrapper = new QueryWrapper<Depository>();
		queryWrapper.eq("shop_id",shopId);
		queryWrapper.eq("goods_name",goodsName);
		Depository depo = depoDao.selectOne(queryWrapper);
		if(depo!=null) {
			Integer currentNum = depo.getGoodsInventory();
			depo.setGoodsInventory(currentNum+num);//可能存在数据溢出问题
			depoDao.updateById(depo);
		}else {
			Depository depository = new Depository();
			depository.setGoodsName(goodsName);
			depository.setShopId(shopId);
			depository.setGoodsInventory(num);
			depository.setUpdateTime(new Date());
			depoDao.insert(depository);
			}
	}
	@Override
	public void depositoryDel(String shopId, String goodsName, Integer num) {
		QueryWrapper<Depository> queryWrapper = new QueryWrapper<Depository>();
		queryWrapper.eq("shop_id",shopId);
		queryWrapper.eq("goods_name",goodsName);
		Depository depo = depoDao.selectOne(queryWrapper);
		if(depo!=null) {//如果存在记录，则减掉对应的数量，并更新记录
			Integer currentNum = depo.getGoodsInventory();
			depo.setGoodsInventory(currentNum-num);//可能存在数据溢出问题
			if(depo.getGoodsInventory()<=0) {//防止小于0
				depo.setGoodsInventory(0);
			}
			depoDao.updateById(depo);
		}
	}
}
